import { get, post, put, del } from "./api.js";

export const jobSeekerService = {
  async getJobSeekers(
    page = 1,
    pageSize = 10,
    searchType = "id",
    keyword = ""
  ) {
    try {
      const params = new URLSearchParams();
      params.append("page", page);
      params.append("pageSize", pageSize);
      params.append("searchType", searchType);
      params.append("keyword", keyword);

      const response = await get(`/job-seekers?${params.toString()}`);

      // 处理后端返回的数据格式
      const data = response.data || response;
      const items = Array.isArray(data) ? data : data.content || [];
      const total = data.totalElements || items.length;
      const totalPages = data.totalPages || Math.ceil(total / pageSize);

      return {
        items,
        total,
        totalPages,
        currentPage: page,
      };
    } catch (error) {
      console.error("Error fetching job seekers:", error);
      throw new Error("获取求职者列表失败");
    }
  },

  async getJobSeeker(id) {
    if (!id) throw new Error("求职者ID不能为空");
    try {
      const response = await get(`/job-seekers/${id}`);
      const data = response.data || response;
      if (!data) throw new Error("求职者不存在");
      return data;
    } catch (error) {
      console.error("Error fetching job seeker:", error);
      throw new Error("获取求职者信息失败");
    }
  },

  async createJobSeeker(data) {
    if (!data.name) throw new Error("姓名不能为空");
    if (!data.email) throw new Error("邮箱不能为空");
    if (!data.phone) throw new Error("电话不能为空");
    try {
      const response = await post("/job-seekers", data, true);
      return response.data || response;
    } catch (error) {
      console.error("Error creating job seeker:", error);
      throw new Error("创建求职者失败");
    }
  },

  async updateJobSeeker(id, data) {
    if (!id) throw new Error("求职者ID不能为空");
    if (!data.name) throw new Error("姓名不能为空");
    if (!data.email) throw new Error("邮箱不能为空");
    if (!data.phone) throw new Error("电话不能为空");
    try {
      const response = await put(`/job-seekers/${id}`, data, true);
      return response.data || response;
    } catch (error) {
      console.error("Error updating job seeker:", error);
      throw new Error("更新求职者失败");
    }
  },

  async deleteJobSeeker(id) {
    if (!id) throw new Error("求职者ID不能为空");
    try {
      const response = await del(`/job-seekers/${id}`);
      return response.data || response;
    } catch (error) {
      console.error("Error deleting job seeker:", error);
      throw new Error("删除求职者失败");
    }
  },

  async batchDeleteJobSeekers(ids) {
    if (!ids || ids.length === 0) throw new Error("请选择要删除的求职者");
    try {
      const response = await post("/job-seekers/batch-delete", { ids }, true);
      return response.data || response;
    } catch (error) {
      console.error("Error batch deleting job seekers:", error);
      throw new Error("批量删除求职者失败");
    }
  },
};
